package com.guomei.utils;

import com.guomei.constans.ResultCode;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;

@Component
public class ValidationUtil {
    private static Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    /**
     * 校验对象
     * @param object 待校验对象
     * @param groups 校验组
     * @param <T> 对象类型
     * @return 校验结果，如果没有违反约束则返回null
     */
    public static <T> Result<?> validate(T object, Class<?>... groups) {
        Set<ConstraintViolation<T>> violations = validator.validate(object, groups);
        if (!violations.isEmpty()) {
            // 返回第一个错误信息
            ConstraintViolation<T> violation = violations.iterator().next();
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), violation.getMessage());
        }
        return null;
    }
    /**
     * Valid input params response object.
     *
     * @param result the result
     * @return the response object
     * @Description: 校验表单输入参数
     * @Author: 陶思宇
     * @CreateDate: 2020 /8/10
     */
    public static Result<?> validInputParams(BindingResult result) {
        if (result == null) {
            return null;
        }
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                return Result.fail(ResultCode.PARAM_ERROR.getCode(), fieldError.getDefaultMessage());
            }
        }
        return null;
    }

    /**
     * 校验对象所有约束
     * @param object 待校验对象
     * @param <T> 对象类型
     * @return 校验错误信息列表
     */
    public static <T> Set<ConstraintViolation<T>> validateAll(T object) {
        return validator.validate(object);
    }

    /**
     * 校验对象指定属性
     * @param object 待校验对象
     * @param propertyName 属性名
     * @param <T> 对象类型
     * @return 校验结果
     */
    public static <T> String validateProperty(T object, String propertyName) {
        Set<ConstraintViolation<T>> violations = validator.validateProperty(object, propertyName);
        if (!violations.isEmpty()) {
            ConstraintViolation<T> violation = violations.iterator().next();
            return violation.getMessage();
        }
        return null;
    }
}
